package com.xiaouyudeguang.common.client;

import com.fasterxml.jackson.databind.JsonNode;
import com.xiaouyudeguang.common.cache.RedisCache;
import com.xiaouyudeguang.common.utils.JsonObject;
import com.xiaouyudeguang.common.utils.RestTemplateUtils;
import com.xiaouyudeguang.common.utils.StringUtils;

import java.util.concurrent.TimeUnit;

public class CommonClient {

    /**
     * 获取微信基础接口的token
     * @param appKey
     * @param appSecret
     * @return
     * @throws Exception
     */
    public static String getToken(String appKey, String appSecret) throws Exception {
        String ACCESS_TOKEN_KEY = "wechat:accessToken:" + appKey;
        String accessToken = RedisCache.get(ACCESS_TOKEN_KEY);
        if (StringUtils.isBlank(accessToken)) {
            String API_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={1}&secret={2}";
            String result = RestTemplateUtils.getForObject(API_URL, String.class, appKey, appSecret);
            JsonNode resultNode = JsonObject.readTree(result);
            if (resultNode != null && resultNode.has("access_token")) {
                accessToken = resultNode.get("access_token").asText();
                RedisCache.set(ACCESS_TOKEN_KEY, accessToken, 90, TimeUnit.MINUTES);
            }
        }
        return accessToken;
    }

    /**
     * 根据openid获取用户信息(需要关注了公众号)
     * @param appKey
     * @param secret
     * @param openid
     * @return
     * @throws Exception
     */
    public static JsonNode getByOpenid(String appKey, String secret, String openid) throws Exception {
        String API_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={1}&openid={2}&lang=zh_CN";
        String result = RestTemplateUtils.getForObject(API_URL, String.class, getToken(appKey, secret), openid);
        return JsonObject.readTree(result);
    }

    /**
     * 根据unionid获取用户信息
     * @param appKey
     * @param secret
     * @param unionid
     * @return
     * @throws Exception
     */
    public static JsonNode getByUnionid(String appKey, String secret, String unionid) throws Exception {
        String API_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={1}&unionid={2}&lang=zh_CN";
        String result = RestTemplateUtils.getForObject(API_URL, String.class, getToken(appKey, secret), unionid);
        return JsonObject.readTree(result);
    }
}
